#!/user/bin/env python3
from fastmcp import FastMCP
mcp_server = FastMCP()
import smtplib
import os
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header

# define mcp tools
@mcp_server.tool()
def hello_you(name):
    '''用于跟人打招呼'''
    print("hello",name)
    return f"你好，{name}！"
@mcp_server.tool()
def send_email_with_attachment(smtp_server, smtp_port, sender_email, sender_password, receiver_email, subject, body, attachment_path=None, use_ssl=True):
    """
    发送带附件的邮件
    
    参数:
        smtp_server: SMTP服务器地址 (如 smtp.qq.com, smtp.163.com)
        smtp_port: SMTP服务器端口 (SSL一般为465，TLS为587)
        sender_email: 发件人邮箱
        sender_password: 发件人邮箱密码或授权码
        receiver_email: 收件人邮箱
        subject: 邮件主题
        body: 邮件正文
        attachment_path: 附件文件路径
        use_ssl: 是否使用SSL加密 (如果端口是465，通常为True)
    """
    # 1. 创建MIMEMultipart对象作为邮件容器
    msg = MIMEMultipart()
    msg['From'] = sender_email  # 使用纯邮箱地址，避免格式问题
    msg['To'] = receiver_email  # 使用纯邮箱地址，避免格式问题
    msg['Subject'] = Header(subject, 'utf-8')
    msg['Message-ID'] = f"<{sender_email.split('@')[0]}.{hash(str(time.time()))}@{sender_email.split('@')[1]}>"
    msg['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S %z")
    
    # 2. 添加邮件正文
    msg.attach(MIMEText(body, 'plain', 'utf-8'))  # 'plain'表示纯文本，可改为'html'发送HTML邮件
    
    # 3. 添加附件
    try:
        with open(attachment_path, 'rb') as f:
            # 使用MIMEApplication可以自动识别文件类型
            attachment_part = MIMEApplication(f.read())
            # 设置附件头信息，filename定义在邮件中显示的名称
            # 修复Windows路径分隔符问题
            filename = os.path.basename(attachment_path)
            attachment_part.add_header('Content-Disposition', 'attachment', filename=filename)
            msg.attach(attachment_part)
    except FileNotFoundError:
        print(f"错误：找不到附件文件 '{attachment_path}'")
        return False

    # 4. 连接SMTP服务器并发送邮件
    try:
        if use_ssl:
            # 使用SSL加密连接 (常见端口465)
            server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=30)
        else:
            # 使用TLS加密连接 (常见端口587)
            server = smtplib.SMTP(smtp_server, smtp_port, timeout=30)
            server.starttls()  # 启用TLS加密[2](@ref)
        
        server.login(sender_email, sender_password)  # 登录邮箱
        
        # 确保收件人是列表格式
        if isinstance(receiver_email, str):
            receiver_list = [receiver_email]
        else:
            receiver_list = receiver_email
            
        server.sendmail(sender_email, receiver_list, msg.as_string())  # 发送邮件
        server.quit()  # 关闭连接
        print("邮件发送成功！")
        return True
    except Exception as e:
        print(f"邮件发送失败: {e}")
        return False
if __name__ == "__main__":
    mcp_server.run(transport="http",host="0.0.0.0",port=5566)

